"use strict";

/**
 * @ngdoc service
 * @name myAppApp.Util
 * @description
 * # Util
 * Service in the myAppApp.
 */
angular
  .module("jgappApp")
  .service("Util", function (
    $document,
    $compile,
    $q,
    $rootScope,
    $timeout,
    $window,
    $location,
    $http,
    openApi,
    localStorageService,
    logList,
    Modulemap,
    ContactInfo
  ) {
    var body = $document.find("body");

    var Util = {
      isOnline: true,
      WZ_MODULE: {
        url: openApi.getRelModule_jwz,
        name: "WZ_MODULE"
      },
      TZFW_MODULE: {
        url: openApi.getRelModule_tzfw,
        name: "TZFW_MODULE"
      },
      AJDJ_MODULE: {
        url: openApi.getRelModule_ajdj,
        name: "AJDJ_MODULE"
      },
      KYZ_MODULE: {
        url: openApi.getRelModule_kyz,
        name: "KYZ_MODULE"
      },
      BG_MODULE: {
        url: openApi.getRelModule_bg,
        name: "BG_MODULE"
      },
      YYSQ_MODULE: {
        url: openApi.getRelModule_yysq,
        name: "YYSQ_MODULE"
      },
      YHKH_MODULE: {
        url: openApi.getRelModule_yhkh,
        name: "YHKH_MODULE"
      },
      FK_MODULE: {
        url: openApi.getRelModule_fk,
        name: "FK_MODULE"
      },
      JK_MODULE: {
        url: openApi.getRelModule_jk,
        name: "JK_MODULE"
      },
      XMBX_MODULE: {
        url: openApi.getRelModule_xmbx,
        name: "XMBX_MODULE"
      },
      CC_MODULE: {
        url: openApi.getRelModule_cc,
        name: "CC_MODULE"
      },
      UC_MODULE: {
        url: openApi.useCarrel,
        name: "UC_MODULE"
      },
      RW_MODULE: {
        url: openApi.getRelModule_rw,
        name: "RW_MODULE"
      },
      TCSQ_MODULE: {
        url: openApi.commisionApplyrel,
        name: "TCSQ_MODULE"
      },
      OTH_MODULE: {
        url: openApi.getRelModule_oth,
        name: "OTH_MODULE"
      },
      COMCON_MODULE: {
        url: openApi.getRelModule_comc,
        name: "COMCON_MODULE"
      },
      CADUIT_MODULE: {
        url: openApi.getRelModule_caduit,
        name: "CADUIT_MODULE"
      },
      BX_MODULE: {
        url: openApi.getRelModule_bx,
        name: "BX_MODULE"
      },
      KK_MODULE: {
        url: openApi.getRelModule_kk,
        name: "KK_MODULE"
      },
      JS_MODULE: {
        url: openApi.getRelModule_js,
        name: "JS_MODULE"
      },
      OFFLINETIP: "当前网络不稳定，请确认网络连接正常",
      READ: "read",
      RETURN: "return",
      DRAFT: "draft",
      CHECK: "check",
      VIEW: "view",
      AUDIT: "aduit",
      MODIFY: "modify",
      ASSIGN: "assign",
      APPEND: "append",
      SYNCHANDLE: "syncHandle",
      SYNCAUDIT: "syncAduit",
      CAUDIT: "caduit",
      UPDATE: "write",
      SYSTEM_NOTICE: "systemNotice",
      init: function () {
        // 验证当前用户是否有权限
        // Util.checkAuth().then(function(data) {
        //   console.log(data);
        //   ContactInfo.getData();
        //   // 先清除审批状态标识
        //   Util.clearTVType();
        //   if (window.jsInterface) {
        //     // 如果是native则初始化
        //     Util.initAngularRouter();
        //   }
        // });

        // 先清除审批状态标识
        if (window.jsInterface) {
          // 如果是native则初始化
          Util.initAngularRouter();
        }
        ContactInfo.getData();
      },
      checkAuth: function () {
        var defer = $q.defer();
        var sign = NativeUtil.getSign();
        $http
          .get(openApi.authlogin, {
            params: sign
          })
          .then(function (data, status, headers, config) {
            if (data.success) {
              defer.resolve(data.success);
            } else {
              Util.Toast("会话过期，请重新登录", {
                callback: function () {
                  NativeUtil.use("login");
                }
              });
            }
          });
        return defer.promise;
      },
      /*
          根据native传过来的param初始化当前的router
        */
      /*
             1. 发的新流程
                1. formKey:用来获取特定流程
                2. id:流程id
                3. processType: NEW
             2. 工作相关流程（带我审批，我发起的流程，和推送的通知类似）
                1. formKey:用来获取特定流程
                2. id:流程id
                3. operationResult:用来确定流程是审批类型
                4. processType:WORK
             3. 查询数据进入的流程
                1. formKey:用来获取特定流程
                2. processType: SEARCH
                3. param:需要的参数
            4. 工作里面应用模块以及设置的页面
                viewName:可直接访问的页面
                processType:CUSTOME

              参数说明
                formKey:用来获取特定流程
                id:流程id
                processType 流程的类型 int
                  ```
                  1 新发起的流程
                  2 待我审批与我发起的流程(推送通知)
                  3 数据查询流程(首页进入)
                  ```
                  operationResult  审批状态
                  ```
                  write – 编辑表单
                  audit – 查看表单
                  syncaduit – 并列或者待领审批
                  caduit – 自定义审批
                  read  - 阅读
                  ```
            */
      initAngularRouter: function (REFEASH) {
        Util.clearTVType();
        var routeConfig = {};
        routeConfig = Util.getRouteConfig();
        // 关闭遮罩层
        $rootScope.$emit("closemasker");
        // 为了触发路径跳转
        routeConfig.timeId = Date.now();
        console.log(routeConfig);
        // 现在初始化页面有两个入口
        // 1. 由消息列表打开
        if (routeConfig.type == "msg") {
          Util.parseConfig(routeConfig);
        } else if (routeConfig.moduleType) {
          // 2. 由页面导航菜单等地方进入,此时又分两种数据
          // (1). 如果是进入工作任务等模块页面
          Util.goModuleView(routeConfig.moduleType, routeConfig.id);
        } else {
          // (2). 如果是打开流程页面
          if (routeConfig.formKey) {
            Util.setformKey(routeConfig.formKey);
          }
          switch (routeConfig.processType) {
            case "NEW": //新发起的流程
              Util.newProcess(routeConfig);
              break;
            case "WORK": //与我相关、运行中等工作中的流程
              Util.workProcess(
                routeConfig.formKey,
                routeConfig.operationResult,
                routeConfig.id
              );
              break;
            case "SEARCH": //数据查询流程
              Util.searchProcess(routeConfig);
              break;
            case "CUSTOME": //工作以及任务签到等页面
              Util.customProcess(routeConfig);
              break;
            default:
          }
        }
        // 如果是直接传参数则刷一下
        if (REFEASH) {
          $rootScope.$apply();
        }
        // 先根据moduleType确定是流程还是非流程
        // 根据processType判断是审批的流程还是新发起的流程或者是数据查询流程
      },
      // if (routeConfig.businessType == Util.SYSTEM_NOTICE) {
      //   // 系统通知
      //   viewName = "/work/systemnotice";
      // } else if (routeConfig.businessType == "workReportNotice") {
      //   // 工作报告type=3为未阅
      //   viewName = "/task/reportdetail/3";
      // } else if (routeConfig.businessType == "workTaskNotice") {
      //   // 工作任务
      //   viewName = "/task/taskdetail";
      // }
      // // 如果是以上三种类型则直接跳转否则其他处理
      // if (viewName) {
      //   $location.path(viewName + "/" + routeConfig.id);
      // } else {
      //   Util.workProcess();
      // }
      parseConfig: function (routeConfig) {
        // 数据类型如下
        //   {
        //     "type" : 'msg',
        //     "data" : {
        //         "msgType"  : 'workTask',
        //         "formData" : {
        //             "params"   : {
        //                 "id"   : "123456"
        //             }
        //         }
        //     }
        // }
        var data = routeConfig.data;
        var msgType = data.msgType;
        var formData = data.formData;
        switch (msgType) {
          case "workFlow": //流程
            Util.workProcess(
              formData.formKey,
              formData.formType,
              formData.params.id
            );
            break;
          case "workTask": //工作任务
            Util.goModuleView(3, formData.params.id);
            break;
          case "workReport": //工作报告
            Util.goModuleView(4, formData.params.id);
            break;
          case "formPage": //表单详情，关联模块相关
            Util.goRelativePageView(formData.formKey, formData.moduleNo);
            break;
          case "outerPage": //外部网页
            var platform = NativeUtil.use("getDeviceInfo").system;
            if (platform == "iOS") {
              NativeUtil.use("openUrl", null, formData.url);
            } else {
              // window.open(formData.url, "_system", "location=no");
              NativeUtil.use("attachPreview", null, formData.url);
            } break;
          case "innerPage": //内部网页
            var flowObj = Modulemap.getViewNameAndIcon(formData.formKey);
            $location
              .path(
                "/webpage/" + flowObj.checkViewName + "/" + routeConfig.timeId
              )
              .replace();
            break;
          default:
        }
      },
      getRouteConfig: function () {
        // var router = $location.search();
        var router = NativeUtil.getUrlParams();
        return router;
      },
      setRouteConfig: function (router) {
        // var router = $location.search();
        NativeUtil.setUrlParams(router);
        return router;
      },
      // 跳转到非流程页面
      goModuleView: function (moduleType, id) {
        var viewName;
        viewName = Modulemap.getModuleViewFromModuleType(moduleType, id);
        if (viewName) {
          $location.path(viewName).replace();
        } else {
          Util.unsupportFlow();
        }
      },
      // 跳转到关联模块流程页面
      goRelativePageView: function (formKey, moduleNo) {
        var moduleName = Modulemap.getViewNameAndIcon(formKey)
        if (!moduleName || (moduleNo == "无" || moduleNo === "")) {
          Util.unsupportFlow();
          return
        }
        var url = "relativePage/" + moduleName.checkViewName + "/" + formKey + "/" + moduleNo;
        Util.setOriginPath(
          url,
          formKey,
          Util.VIEW
        );
        $location.path(url).replace()
      },
      // 页面跳转处理
      newProcess: function (routeConfig) {
        var flowObj;
        flowObj = Modulemap.getViewNameAndIcon(routeConfig.formKey);
        if (flowObj.viewName) {
          $location.path(flowObj.viewName + "/" + routeConfig.id).replace();
        } else {
          Util.unsupportFlow();
        }
      },
      customProcess: function (routeConfig) {
        var viewName = Modulemap.getViewNameAndIcon(routeConfig.viewName);
        if (viewName) {
          $location.path(viewName).replace();
        } else {
          Util.unsupportFlow();
        }
      },
      unsupportFlow: function () {
        Util.Toast("移动端暂不支持该流程的审批，请您在电脑上完成该操作", {
          callback: function () {
            Util.goBack();
            NativeUtil.use("close");
          },
          time: 1000
        });
      },
      searchProcess: function (routeConfig) {
        var flowObj;
        flowObj = Modulemap.getViewNameAndIcon(routeConfig.formKey);
        if (flowObj.checkViewName) {
          // 网页形式的流程先这么来
          if (routeConfig.formKey == "Other_Placard") {
            $location
              .path(
                "/webpage/" + flowObj.checkViewName + "/" + routeConfig.timeId
              )
              .replace();
          } else {
            $location
              .path(
                "/search/" + flowObj.checkViewName + "/" + routeConfig.timeId
              )
              .replace();
            Util.setOriginPath(
              flowObj.checkViewName +
              "/" +
              routeConfig.timeId +
              "/" +
              routeConfig.id,
              routeConfig.formKey,
              routeConfig.operationResult
            );
          }
          Util.setTVType(Util.READ);
        } else {
          Util.unsupportFlow();
        }
      },
      workProcess: function (formKey, operationResult, id) {
        var flowObj, viewName;
        flowObj = Modulemap.getViewNameAndIcon(formKey);
        switch (operationResult) {
          case "check": //未批复
            Util.setTVType(Util.CHECK);
            viewName = flowObj.checkViewName;
            break;
          case "write": //未批复
            Util.setTVType(Util.UPDATE);
            viewName = flowObj.viewName;
            break;
          case "read": //只读
            Util.setTVType(Util.READ);
            viewName = flowObj.checkViewName;
            break;
          case "aduit": //审批
          case "syncHandle": //审批
            Util.setTVType(Util.AUDIT);
            viewName = flowObj.checkViewName;
            break;
          case "append": //审批
            Util.setTVType(Util.APPEND);
            switch (formKey) {
              case "Finance_ProjectMoney":
                viewName = "finance/checkf_gck_append";
                break;
              case "Xm_ProjectPayment":
                viewName = "project/check_payment_append";
                break;
              case "Xm_ProjectCost":
                viewName = "project/check_deduct_append";
                break;
              default:
                viewName = flowObj.checkViewName;
                break;
            }
            break;
          case "caduit": //自定义流程审批
            Util.setTVType(Util.CAUDIT);
            viewName = flowObj.checkViewName;
            break;
          case "syncAduit": //并行审批
            Util.setTVType(Util.SYNCAUDIT);
            viewName = flowObj.checkViewName;
            break;
          case "view": //自定义流程审批
            Util.setTVType(Util.VIEW);
            viewName = flowObj.checkViewName;
            break;
          case "return": //自定义流程审批
            // 还车
            Util.setTVType(Util.RETURN);
            viewName = flowObj.returnViewName;
            break;
          case "modify":
            // 采购物资流程编辑物资的审批任务 
            Util.setTVType(Util.MODIFY);
            viewName = flowObj.checkViewName;
            break;
          case "assign":
            // 用车申请增加一个分配司机的表单类型assign，在这个表单里面可以修改车牌号码和驾驶员信息这两个字段 
            Util.setTVType(Util.ASSIGN);
            viewName = flowObj.checkViewName;
            break;
          default:
        }
        if (viewName) {
          $location.path(viewName + "/" + id);
          Util.setOriginPath(viewName + "/" + id, formKey, operationResult);
        } else {
          Util.unsupportFlow();
        }
      },
      /**
       * 获取当前视图名字
       * @return [type] [视图名]
       */
      getCurPageViewName: function () {
        var routeConfig, viewName;
        routeConfig = Util.getRouteConfig();
        if (routeConfig.moduleType) {
          viewName = Modulemap.getModuleValueFromModuleType(
            routeConfig.formKey
          );
        } else {
          viewName = Modulemap.getViewName(routeConfig.formKey);
        }
        return viewName;
      },
      /**
       * [设置每次页面跳转后的formkey与id]
       * @param  {[type]} path [description]
       * @return [type]        [description]
       */
      setOriginPath: function (path, formKey, formType) {
        var route = {};
        $rootScope.originConfig = $rootScope.originConfig || [];
        route.path = path;
        route.formType = formType;
        route.formKey = formKey;
        $rootScope.originConfig.push(route);
      },
      /**
       * 将路由与operationResult关联起来
       * @return [type] [description]
       */
      handleHashchange: function () {
        var path, routeConfig, curRoute;
        routeConfig = Util.getRouteConfig();
        path = $location.path();
        if (
          path &&
          $rootScope.originConfig &&
          $rootScope.originConfig.length > 0
        ) {
          $rootScope.originConfig.forEach(function (item, index) {
            if (item.path.indexOf(path.slice(1)) > -1) {
              return (curRoute = item);
            }
          });
        }
        if (curRoute) {
          Util.setTVType(curRoute.formType);
          Util.setformKey(curRoute.formKey);
        }
      },
      isFile: function (v) {
        return /(.+)\.(docx|ppt|doc|xls|zip|rar|xlsx|et|pptx|pdf|wps|txt)$/gi.test(
          v
        );
      },
      isImg: function (v) {
        return /(.+)\.(jpg|png|gif|jpeg)$/gi.test(v);
      },
      isImage: function (type) {
        switch (type) {
          case 'png':
          case 'jpg':
          case 'gif':
          case 'jpeg':
            return true;
          default:
            return false;
        }
      },
      openExpress: function (id) {
        $location.path("/openfile/openfile/express/" + id);
        // window.open(url, '_system', 'location=no');
      },
      getPlatform: function () {
        var deviceInfo = NativeUtil.use("getDeviceInfo");
        return deviceInfo.system;
      },
      Toast: function (info, option) {
        var time = (option && option.time) || 2000;
        var icon = (option && option.icon) || "";
        if (icon) {
          var iconsrc = "images/" + icon;
          icon = "<img src='" + iconsrc + "'/>";
        }
        var modalStr =
          '<div class="masker nobg toast-masker">' +
          '<div class="fade toast-wrapper">' +
          icon +
          info +
          "</div>" +
          "</div>";
        var modalEl = angular.element(modalStr);
        var scope = (option && option.scope) || $rootScope.$new();
        $compile(modalEl)(scope);
        body.append(modalEl);
        $timeout(function () {
          modalEl.remove();
          option && option.callback && option.callback.call(scope);
        }, time);
      },
      showAudit: function (option) {
        var scope = (option && option.scope) || $rootScope.$new();
        var auditContainer = angular.element(
          document.querySelector("div[ng-view]")
        );
        var temp =
          '<div class="flex footer tc flow-btn" style="display: flex;">' +
          '<div class="{{item.className}}" style="flex:1" ng-click="check(item)" ng-repeat="item in TaskReview.result.operations"> ' +
          '<span class="icon"></span><span class="name" ng-click="showAuditContent(item,$event)">{{item.name}}</span> </div>' +
          '<div class="more-btn" style="flex:1" ng-click="checkmore(item)" ng-show="TaskReview.result.moreOperations.length>0"> ' +
          '<div class="more-btns-list" ng-hide="hidedisagree"><div class="name" ng-repeat="item in TaskReview.result.moreOperations" ng-click="showAuditContent(item,$event)">{{item.name}}</div> </div></div>' +
          "</div>";
        //We don't have the scope we're gonna use yet, so just get a compile function for modal
        var modalEl = angular.element(temp);
        $compile(modalEl)(scope);
        auditContainer.append(modalEl);
      },
      showAuditContent: function (option) {
        var container = angular.element(document.querySelector("div[ng-view]"));
        var contenttemplate =
          '<div class="audit-wrapper section list" ng-show="showDailog">' +
          '<div class="audit-title">{{btnTitle}}</div>' +
          '<div class="audit-content"><textarea cols="30" rows="10" ng-model="auditText" maxLength="500" placeholder="请输入审批意见，字数不超过500"></textarea>' +
          '<div class="pd10 icon_enter" ng-click="copyto()">抄送给: {{aduitUserNames}}</div>' +
          '<div class="f_sk" file-upload file-data="attachmentName" hidelabel="true"></div>' +
          "</div>" +
          '<div class="audit-btn flex tc">' +
          '<div class="confirm" ng-click="confirm()">确定</div>' +
          '<div class="cancel" ng-click="cancel()">取消</div>' +
          "</div>" +
          "</div>";
        //We don't have the scope we're gonna use yet, so just get a compile function for modal
        $rootScope.contenttemplate = angular.element(contenttemplate);
        var scope = (option && option.scope) || $rootScope.$new();
        $compile($rootScope.contenttemplate)(scope);
        container.append($rootScope.contenttemplate);
      },
      showFlowTransfer: function (option) {
        var container = angular.element(document.querySelector("div[ng-view]"));
        var contenttemplate =
          '<div flow-transfer taskid="taskId"></div>'
        $rootScope.transfertemplate = angular.element(contenttemplate);
        var scope = (option && option.scope) || $rootScope.$new();
        $compile($rootScope.transfertemplate)(scope);
        container.append($rootScope.transfertemplate);
      },
      showFallbackFlow: function (option) {
        var container = angular.element(document.querySelector("div[ng-view]"));
        var contenttemplate =
          '<div fall-back taskid="taskId"></div>'
        $rootScope.fallbacktemplate = angular.element(contenttemplate);
        var scope = (option && option.scope) || $rootScope.$new();
        $compile($rootScope.fallbacktemplate)(scope);
        container.append($rootScope.fallbacktemplate);
      },
      showRemindBtn: function (option) {
        var scope = (option && option.scope) || $rootScope.$new();
        var auditContainer = angular.element(
          document.querySelector("div[ng-view]")
        );
        var temp = '<div flow-remind taskid="process_id"></div>';
        //We don't have the scope we're gonna use yet, so just get a compile function for modal
        var modalEl = angular.element(temp);
        $compile(modalEl)(scope);
        auditContainer.append(modalEl);
      },
      frequentConcern: function (option) {
        $rootScope.$emit("showmasker");
        var container = angular.element(document.querySelector("div[ng-view]"));
        var template =
          '<div class="users-masker">' +
          ' <div class="list pickceritem" style="background:#fff">' +
          '   <p class="info-title">抄送人</p>' +
          '<div class="search_input_wrapper">' +
          '<input type="text" class="search_input" ng-model="searchinput" ng-model-options="{ debounce: 1000 }" ng-change="search2()" placeholder="搜索">' +
          "</div>" +
          '   <div class="user-list">' +
          '     <div class="list-item" ng-repeat="item in users" ng-click="selectUsers(item)">' +
          "{{item.name}}({{item.position}})" +
          '<input type="checkbox" class="radio fr" value="{{item}}" ng-model="item.selected" ng-change="Chooseuser.handleUser(item)">' +
          "</div>" +
          "</div>" +
          "<div class='btn mt10' ng-click='chooseusers()'>确定</div>" +
          "</div>" +
          "</div>";
        //We don't have the scope we're gonna use yet, so just get a compile function for modal
        $rootScope.usersEl = angular.element(template);
        var scope = (option && option.scope) || $rootScope.$new();
        $compile($rootScope.usersEl)(scope);
        container.after($rootScope.usersEl);
        $rootScope.$on("closemasker", function () {
          $rootScope.usersEl.remove();
        });
      },
      perlist: function (option) {
        $rootScope.$emit("showmasker");
        var container = angular.element(document.querySelector("div[ng-view]"));
        var template = '<div class="list-modal list table-list f_sk">' +
          '	<div class="search_input_wrapper">' +
          '<input type="text" class="search_input" ng-model="filterSql" ng-model-options="{ debounce: 1000 }" ng-change="search(filterSql)" placeholder={{placeholder}}></div>' +
          '<div class="table-item" ng-click="choosePeople($index)" ng-class="{\'selected\':item.selected}" ng-repeat="item in sptypes">' +
          '<div class="list-item" ng-repeat="(key,value) in porlist">' +
          '<div class="item-label">{{key}}</div>' +
          '<div class="flow-content">{{item[value.name]|listvalueFmt:value.value}}</div>' +
          '</div>' +
          '</div>' +
          '</div>'
        //We don't have the scope we're gonna use yet, so just get a compile function for modal
        if ($rootScope.perEl) {
          $rootScope.perEl.remove();
        }
        $rootScope.perEl = angular.element(template);
        var scope = (option && option.scope) || $rootScope.$new();
        $compile($rootScope.perEl)(scope);
        container.after($rootScope.perEl);
        $rootScope.$on("closemasker", function () {
          $rootScope.perEl.remove();
        });
      },
      closeMasker: function (option) {
        $rootScope.$emit("closemasker");
      },
      insertRelList: function (option) {
        $rootScope.commonEl && $rootScope.commonEl.remove();
        $rootScope.commonEl = null;
        var container = angular.element(
          document.querySelector(".log-list").previousElementSibling
        );
        // 审批人
        var aduitUserNamestemplate =
          '<div class="section"><div class="list-item flex" ng-show="TaskReview.result.aduitUserNames">' +
          '<div class="w40 c9">审批人员</div>' +
          '<div class="w60">{{TaskReview.result.aduitUserNames|aduituserfilter}}</div></div></div>';
        // 关联模块模版
        var template =
          '<div rel-list form-key="formKey" data="TaskReview.result"></div>';
        var file_module_template =
          '<div file-module form-key="formKey" ref-id="TaskReview.result.uid"></div>';
        // 追加备注模版
        var remark_list_template =
          '<div remark-list form-key="formKey" dataid="TaskReview.result.uid"></div>';
        var remark_input_template =
          '<div remark-input uid="TaskReview.result.uid"></div>';
        var comment_input_template =
          '<div flowcomment uid="TaskReview.result.uid"></div>';
        //We don't have the scope we're gonna use yet, so just get a compile function for modal
        $rootScope.commonEl = angular.element(
          aduitUserNamestemplate +
          template +
          remark_input_template +
          remark_list_template +
          file_module_template +
          comment_input_template
        );
        var scope = (option && option.scope) || $rootScope.$new();
        $compile($rootScope.commonEl)(scope);
        container.after($rootScope.commonEl);
      },

      insertAduitUsers: function (option) {
        $rootScope.commonEl && $rootScope.commonEl.remove();
        $rootScope.commonEl = null;
        var container = angular.element(
          document.querySelector(".log-list").previousElementSibling
        );
        // 审批人
        var aduitUserNamestemplate =
          '<div class="section"><div class="list-item flex" ng-show="TaskReview.result.aduitUserNames">' +
          '<div class="w40 c9">审批人员</div>' +
          '<div class="w60">{{TaskReview.result.aduitUserNames|aduituserfilter}}</div></div></div>';
        $rootScope.commonEl = angular.element(
          aduitUserNamestemplate
        );
        var scope = (option && option.scope) || $rootScope.$new();
        $compile($rootScope.commonEl)(scope);
        container.after($rootScope.commonEl);
      },

      insertRemarkList: function (option) {
        $rootScope.relistEl && $rootScope.relistEl.remove();
        $rootScope.relistEl = null;
        var container = angular.element(
          document.querySelector(".log-list").previousElementSibling
        );
        var remark_input_template =
          '<div remark-input uid="TaskReview.result.uid"></div>';
        // 追加备注模版
        var remark_list_template =
          '<div remark-list form-key="formKey" dataid="TaskReview.result.uid"></div>';
        //We don't have the scope we're gonna use yet, so just get a compile function for modal
        $rootScope.relistEl = angular.element(
          remark_input_template + remark_list_template
        );
        var scope = (option && option.scope) || $rootScope.$new();
        $compile($rootScope.relistEl)(scope);
        container.after($rootScope.relistEl);
      },
      showAddFile: function (option) {
        var container = angular.element(
          document.querySelector(".expressNo,.log-list")
        );
        var template =
          '<div class="file-upload" file-upload file-data="attachmentName" maxnum=1></div>';
        //We don't have the scope we're gonna use yet, so just get a compile function for modal
        var modalEl = angular.element(template);
        var scope = (option && option.scope) || $rootScope.$new();
        $compile(modalEl)(scope);
        container.after(modalEl);
      },
      isNullObj: function (data) {
        var testData = true;
        if (angular.isArray(data)) {
          testData = !data.length;
        }
        if (angular.isObject(data)) {
          testData = !Object.keys(data).length;
        }
        return testData;
      },
      checkDays: function (data) {
        var check = true;
        if ((data * 10) % 5 !== 0) {
          check = false;
        }
        return check;
      },
      checkNum: function (data) {
        var check = true;
        if ((data * 10) % 10 !== 0) {
          check = false;
        }
        return check;
      },
      checkrlNum: function (data) {
        return data > 0;
      },
      logout: function () {
        // Util.checkAuth();
        Util.Toast("会话过期，请重新登录", {
          callback: function () {
            NativeUtil.use("login");
          }
        });
      },
      // 获取各种类别的key,value值
      getKeyValue: function (param, callback) {
        var data = localStorageService.get(JSON.stringify(param));
        if (data && callback) {
          callback(data);
          return;
        }
        $http({
          method: "GET",
          url: openApi.getKeyType,
          params: param
        }).then(
          function (data, status, headers, config) {
            console.log(data);
            data = data.data; if (data.logout) {
              Util.logout();
              return;
            }
            if (data.success) {
              // 底部关联文件获取
              localStorageService.set(JSON.stringify(param), data);
              if (callback) {
                callback(data);
              }
            }
          },
          function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
          }
        );
      },
      getPerformanceList: function (param, callback) {
        $http
          .get(param.url + "?id=" + param.params.id)
          .then(function (data, status, headers, config) {
            console.log(data);
            data = data.data; if (data.logout) {
              Util.logout();
              return;
            }
            if (data.success) {
              if (callback) {
                callback(data);
              }
            }
          });
      },
      getModuleRel: function (relModule, callback) {
        var relModuleData = localStorageService.get(
          "relModuleData" + relModule.name
        );
        if (relModuleData && relModuleData.success) {
          if (callback) {
            callback(relModuleData);
            return;
          }
        }
        $http
          .get(relModule.url)
          .then(function (data, status, headers, config) {
            console.log(data);
            data = data.data; if (data.logout) {
              Util.logout();
              return;
            }
            if (data.success) {
              localStorageService.set("relModuleData" + relModule.name, data);
              if (callback) {
                callback(data);
              }
              // 底部关联文件获取
            }
          });
      },
      // 获取证件类别
      getcerTypeList: function (param, callback) {
        var cerkeyTypeList = localStorageService.get("cerkeyTypeList");
        if (cerkeyTypeList && cerkeyTypeList.success) {
          if (callback) {
            callback(cerkeyTypeList);
            return;
          }
        }
        $http
          .post(openApi.getCerkey, param)
          .then(function (data, status, headers, config) {
            data = data.data; if (data.logout) {
              Util.logout();
              return;
            }
            if (data.success) {
              // 类别列表，用来过滤
              localStorageService.set("cerkeyTypeList", data);
              if (callback) {
                callback(data);
              }
            } else {
              Util.Toast(data.result || "操作失败，请稍后尝试", {
                time: 5000
              });
            }
          });
      },
      /*
       *type='check'(待审批=已通过=审核中用于查看)
       *type='audit'(用于审核)
       *type='write'(用于修改)
       */
      setTVType: function (type) {
        localStorageService.set("TVType", type);
      },
      getTVType: function () {
        var type;
        type = localStorageService.get("TVType");
        return type;
      },
      clearTVType: function () {
        localStorageService.remove("TVType");
      },
      // 设置关联模块层级，有利于返回最后才删除
      setRelMoNum: function (type) {
        var num;
        num = localStorageService.get("RelMoNum") || 0;
        // 源type,最开始点击进去时候保留当前的type，之后所有的type都是check
        var TVtype = localStorageService.get("sourceTVtype");
        if (!TVtype) {
          TVtype = Util.getTVType();
          localStorageService.set("sourceTVtype", TVtype);
          Util.setTVType(Util.CHECK);
        }
        if (type) {
          num++;
        } else {
          num--;
          if (num == 0) {
            var TVtype = localStorageService.get("sourceTVtype");
            localStorageService.remove("sourceTVtype");
            Util.setTVType(TVtype);
          }
        }
        localStorageService.set("RelMoNum", num);
        return num;
      },
      getRelMoNum: function (type) {
        var num;
        num = localStorageService.get("RelMoNum") || 0;
        return num;
      },
      // 保存回显数据
      savaParamForReview: function (params, form_id) {
        params.form_id = form_id;
        localStorageService.set("paramsforReview", params);
      },
      // 获取回显数据
      getParamForReview: function (form_id) {
        var returnData = {};
        var data = localStorageService.get("paramsforReview");
        // 如果当前id与页面id一致则返回
        if (data && data.form_id == form_id) {
          returnData = data;
        }
        return returnData;
      },
      goBack: function () {
        $window.history.back();
        $rootScope.$emit("closemasker");
      },
      // 清除回显数据
      clearParamForReview: function (form_id) {
        localStorageService.remove("paramsforReview");
      },
      // 保存查询参数
      savaDataforsearch: function (params) {
        localStorageService.set("selectedObj", params);
      },
      // 获取已经选择好的参数
      getDataforsearch: function () {
        var data = localStorageService.get("selectedObj") || {};
        return data;
      },
      // 获取已经选择好的参数
      clearDataforsearch: function () {
        localStorageService.remove("selectedObj");
      },
      // property给出时候filter中只有一个值
      filterSelectData: function (data, filter, property) {
        var result = {};
        for (var i in filter) {
          var tempData = data;
          if (property) {
            result[property] = data[i];
          } else {
            // 当属姓名是包含着对象时候
            var arr = i.split(".");
            var temp;
            while (arr.length > 0) {
              temp = arr.shift();
              tempData = tempData && tempData[temp] || "";
            }
            result[filter[i]] = tempData;
          }
        }
        return result;
      },
      saveSelectLists: function (data) {
        localStorageService.set("selectLists", data);
      },
      getSelectLists: function () {
        var selectLists;
        selectLists = localStorageService.get("selectLists");
        return selectLists;
      },
      clearSelectListsh: function () {
        localStorageService.remove("selectLists");
      },
      clearFormData: function () {
        Util.clearParamForReview();
        Util.clearDataforsearch();
        // 证件信息
        Util.clearSelectListsh();
        // 审批人员信息
        Util.clearLocalInfo("SPperson");
        // 如果清除掉会导致关联模块调转回来时候获取不到值
        // Util.clearTVType();
      },
      getformKey: function () {
        return localStorageService.get("formkey");
      },
      setformKey: function (formkey) {
        localStorageService.set("formkey", formkey);
      },
      saveLocalInfo: function (key, data) {
        localStorageService.set(key, data);
      },
      getLocalInfo: function (key) {
        var data;
        data = localStorageService.get(key) || {};
        return data;
      },
      clearLocalInfo: function (key) {
        localStorageService.remove(key);
      },
      mergeArr: function (dist, src, type) {
        var destArr = [];
        if (Array.isArray(src)) {
          if (src.length < 1) {
            return dist;
          }
        } else {
          return dist;
        }
        dist.forEach(function (distitem, index) {
          var check = false;
          src.forEach(function (srcitem, index) {
            if (distitem[type] == srcitem[type]) {
              check = true;
            }
          });
          if (!check) {
            destArr.push(distitem);
          }
        });
        dist = src.concat(destArr);
        return dist;
      },
      getkeyFromValue: function (obj, value) {
        for (var index = 0; index < obj.length; index++) {
          var item = obj[index];
          if (item.value == value) {
            return item.key
          }
        }
      },
      getValueFromkey: function (obj, key) {
        for (var index = 0; index < obj.length; index++) {
          var item = obj[index];
          if (item.key == key) {
            return item.value
          }
        }
      },
      getDetailData: function (id, callback) {
        var TVtype;
        TVtype = Util.getTVType(); //根据页面的来源来判断是发起的流程还是修改的流程，如果是发起的则不管，如果是修改的则获取数据用来回显
        var result, selectData;
        result = Util.getParamForReview(id);
        selectData = Util.getDataforsearch();
        Util.clearDataforsearch()
        // 如果有两个选择项目的话selectTabContent的值不固定
        // 关联模块名称
        // result.relatedModuleName = selectData.selectTabContent || "";
        // 关联模块标识
        // result.relatedModule = selectData.selectTab || "";
        result = angular.extend(result, selectData.filterData);
        result.disableInput = !!(
          selectData.filterData && Object.keys(selectData.filterData).length
        );
        // 如果有缓存则用缓存，没有缓存则判断如果要回显则请求数据否则发起流程不管
        if (TVtype == Util.UPDATE && !result.taskId) {
          var param = {};
          param.taskId = id;
          $http
            .get(openApi.getTaskInfo, {
              params: param
            })
            .then(function (data, status, headers, config) {
              data = data.data; if (data.logout) {
                Util.logout();
                return;
              }
              if (data.success) {
                var param = {};
                param.taskId = data.result.task && data.result.task.id;
                param.operationId = data.result.operations[0].id;
                var key = data.result.formKey || data.result.currentObjectName;
                if (!data.result[key]) {
                  // 提交时候发生了异常key值都在task上面
                  key = "task";
                  Util.Toast(
                    "该流程在提交的过程中出现异常，请在电脑上删除该条数据并重新发起！", {
                    callback: function () {
                      NativeUtil.use("close");
                    },
                    time: 5000
                  }
                  );
                }
                var result = angular.extend(data.result[key], param);
                console.log(result);
                if (callback) {
                  callback(result);
                }
              } else {
                Util.Toast(data.result, {
                  callback: function () {
                    NativeUtil.use("close");
                  },
                  time: 5000
                });
              }
            });
          // 清掉页面来源数据
          // Util.clearTVType()
        } else {
          if (callback) {
            callback(result);
          }
        }
      },
      showloglist: function (id, callback) {
        var TVtype;
        var logUrl;
        TVtype = Util.getTVType();
        // 如果是草稿或者没有类型则不显示审批记录
        if (!TVtype || TVtype == Util.DRAFT) {
          return;
        }
        switch (TVtype) {
          case Util.CHECK: //待审批
          case Util.READ: //无需审批
            logUrl = openApi.myProcessLog;
            break;
          case Util.AUDIT:
          case Util.UPDATE: //未批复
          case Util.SYNCAUDIT: //并行审批
          case Util.CAUDIT: //自定义流程审批
          case Util.APPEND: //自定义流程审批
          case Util.MODIFY: //物资采购
          case Util.RETURN: //还车
            logUrl = openApi.myProcessLogA;
            break;
          default:
            logUrl = openApi.myProcessLog;
        }
        var options = {};
        options.param = {};
        options.url = logUrl;
        options.param.processId = id;
        options.param.taskId = id;
        logList.getData(options).then(function (data) {
          callback && callback(data);
        });
      },
      calcDistance: function (v) {
        var str = "";
        if (v) {
          str = "距离考勤地点";
          if (v >= 1000) {
            str = str + (v / 1000).toFixed(1) + "公里";
          } else {
            str = str + v + "米";
          }
        }
        return str;
      }
    };
    return Util;
  });
